<?php


namespace app\api\service;

use app\common\enum\FlagEnum;
use app\common\enum\OrderStatusEnum;
use think\Db;
use think\Loader;
use think\Log;
use app\api\model\Order as OrderModel;
use app\api\service\Order as OrderService;
use app\api\model\Product as ProductModel;
use app\api\model\Sku as SkuModel;

Loader::import('wechat.WxPay', EXTEND_PATH, '.Api.php');

class Notify extends \WxPayNotify
{
    public function NotifyProcess($objData, $config, &$msg)
    {
        $data = $objData->GetValues();
        if($data['result_code'] == 'SUCCESS')
        {
            $order_no = $data['out_trade_no'];
            Db::startTrans();
            try {
                $order = OrderModel::where('order_no', '=', $order_no)->lock(true)->find();
                if($order->status == 1)
                {
                    $service = new OrderService();
                    $status = $service->checkOrderStatus($order->id);
                    if($status['pass'])
                    {
                        $this->updateOrderStatus($order->id, true);
                        $this->reduceStock($status);
                    }
                    else
                    {
                        $this->updateOrderStatus($order->id, false);
                    }
                }
                Db::commit();
                return true;
            }catch (\Exception $ex) {
                Db::rollback();
                Log::error($ex);
                return false;
            }
        }else{
            return true;
        }
    }

    //减库存，减单规格商品库存，减多规格商品库存
    private function reduceStock($status)
    {
        foreach($status['p_status_array'] as $single_status)
        {
            //减单规格商品库存product表
            if($single_status['flag'] == FlagEnum::Single){
                ProductModel::where('id', '=', $single_status['id'])->setDec('stock', $single_status['count']);
            }
            //减多规格商品库存sku表
            if($single_status['flag'] == FlagEnum::Multiple){
                SkuModel::where('id', '=', $single_status['id'])->setDec('stock', $single_status['count']);
            }
        }
    }

    private function updateOrderStatus($orderID, $success)
    {
        $s = $success ? OrderStatusEnum::PAID : OrderStatusEnum::PAID_BUT_OUT_OF;
        OrderModel::where('id', '=', $orderID)->update(['status' => $s]);
    }
}